const express = require('express');
const bodyParser = require('body-parser');// 解析body字段模块
const morgan = require('morgan'); // 命令行log显示
const mongoose = require('mongoose');
const passport = require('passport');// 用户认证模块passport
const routes = require('./routes');
const config = require('./config');
var session = require('express-session');
const useatlas = false;
var PORT = 8081;
var DB = useatlas ? config.atlasuri : config.database;
var path = require('path');
global.appRoot = path.resolve(__dirname);
/**
 * Initialise log4js first, so we don't miss any log messages
 */
const log4js = require('log4js');
log4js.configure('./config/log4js.json');
const logger = log4js.getLogger("startup");

const port = process.env.PORT || PORT;

console.log('DB=' + DB)

const app = express();

//to resolve the cors problem
const cors = require('cors')
app.use(cors())

/* another way
const allowCrossDomain = function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
  res.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Session-Token");
  next();
}
app.use(allowCrossDomain);
*/

/* white name list
const whiteName = ['http://localhost:8083', 'http://localhost:8084']
app.use(cors({
  credential:true,
  origin:whiteName
}))
*/

app.use('/', express.static(__dirname + '/doc'));
app.use('/html', express.static(__dirname + '/html'));
app.use('/public', express.static(__dirname + '/public/'));
app.use(passport.initialize());// 初始化passport模块
app.use(morgan('dev'));// 命令行中显示程序运行日志,便于bug调试
app.use(bodyParser.urlencoded({extended: true, limit: '50mb', parameterLimit: 50000}));
app.use(bodyParser.json({limit: '50mb', extended: true})); // 调用bodyParser模块以便程序正确解析body传入值
app.use(express.static('public'));
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: {secure: false, maxAge: 60 * 60 * 1000}
}))

routes(app);

mongoose.Promise = global.Promise;
mongoose.connect(DB, {useNewUrlParser: true}); // 连接数据库


var server = app.listen(port, () => {
  logger.info('Express server listening on port ', server.address().port, " with pid ", process.pid);
  console.log('listening on port : ' + port);
})

module.exports.port = port;

